package com.freshmarket.freshmarket.service.impl;

import com.freshmarket.freshmarket.controller.form.UserRegisterForm;
import com.freshmarket.freshmarket.entity.User;
import com.freshmarket.freshmarket.dao.UserMapper;
import com.freshmarket.freshmarket.exception.MyException;
import com.freshmarket.freshmarket.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.freshmarket.freshmarket.utils.EncryptUtil;
import com.freshmarket.freshmarket.utils.Result;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Squirrel
 * @since 2020-09-04
 */
@Service
public class UserServiceImpl  implements IUserService {

    @Resource
    private UserMapper userMapper;
    @Override
    public Result register(UserRegisterForm userRegisterForm) throws Exception {
        if(!userRegisterForm.getUserPassword().equals(userRegisterForm.getUserRePassword())){
            return new Result(false,444,"两次密码不一致！",null);
        }else{
            //通过电话判断该用户是否已经存在
            User user = new User();
            user.setUserName(userRegisterForm.getUserName());
            user.setUserPassword(userRegisterForm.getUserPassword());
            user.setUserPhone(userRegisterForm.getUserPhone());
            User userPhone = userMapper.selectByPhone(user.getUserPhone());
            if(userPhone != null){
                //该用户已经存在
                return new Result(false,444,"该用户已经存在！",null);
            }else{
               //执行新增
                //密码加密
                String pws = EncryptUtil.encrypt(user.getUserPassword());
                int row = userMapper.insertUser(user.getUserName(), user.getUserPhone(), pws);
                if(row > 0){
                    return new Result(true,200,"注册成功！",null);
                }else{
                    return new Result(false,444,"注册失败！",null);
                }
            }
        }

    }

    //记录当前用户的登录时间
    @Override
    public Result recordTime(String userPhone, String userLastLogintime) throws Exception {
        int row = userMapper.updateTime(userPhone, userLastLogintime);
        if(row>0){
            return new Result(true,200,"登录成功！",null);
        }else{
            return new Result(false,444,"登录失败！",null);

        }

    }

    @Override
    public Result selectUser(Integer userId) throws Exception {
        User user = userMapper.selectById(userId);
        if(user!=null){
            return new Result(true,200,"查询成功！",user);
        }else{
            throw new MyException("查询失败");
        }
    }
}
